package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.EmployeeProfileCacheMapper;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Model.Dto.EmployeeProfileDto;
import aiku.numericalcontroloa.Model.Entity.BaseEntity;
import aiku.numericalcontroloa.Model.Entity.EmployeeProfileCache;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Vo.EmployeeProfileInfoVo;
import aiku.numericalcontroloa.Model.Vo.EmployeeProfileVo;
import aiku.numericalcontroloa.enums.RoleEnum;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.EmployeeProfile;
import aiku.numericalcontroloa.Service.EmployeeProfileService;
import aiku.numericalcontroloa.Mapper.EmployeeProfileMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author 马
* @description 针对表【employee_profile】的数据库操作Service实现
* @createDate 2024-01-16 14:25:10
*/
@Service
public class EmployeeProfileServiceImpl extends ServiceImpl<EmployeeProfileMapper, EmployeeProfile>
    implements EmployeeProfileService{
    @Autowired
    private EmployeeProfileMapper employeeProfileMapper;
    @Autowired
    private EmployeeProfileCacheMapper profileCacheMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageNotificationMapper msgNotificationMapper;

    /**
     * @description: 添加员工档案
     * @param: [employeeProfile]
     * @return: boolean
     */
    @Override
    public Result addEmployeeProfile(EmployeeProfile employeeProfile) {
        if (employeeProfile == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        if (employeeProfile.getUserId() == null || employeeProfile.getUserId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        // 查该员工是否已有合同
        LambdaQueryWrapper<EmployeeProfile> profileLQW = new LambdaQueryWrapper<>();
        profileLQW.eq(EmployeeProfile::getUserId,employeeProfile.getUserId());
        EmployeeProfile profile = employeeProfileMapper.selectOne(profileLQW);
        if (profile != null){
            return new Result(HttpStatus.BAD_REQUEST,"已有该员工档案");
        }
        // 修改状态，1审核通过
        employeeProfile.setEmployeeUpdateStatus(1);
        // 修改次数默认0
        employeeProfile.setEmployeeUpdateCount(0);
        // 合同到期提醒，提前一个月
        // 获取一个月前的日期
        LocalDate oneMonthAgo = employeeProfile.getEmployeeContractDate().minusMonths(1);
        employeeProfile.setEmployeeContractRemindDate(oneMonthAgo);
        employeeProfileMapper.insert(employeeProfile);
        return Result.success("添加成功");
    }

    /**
     * @description: 员工申请修改职工档案,如果是管理员修改则直接修改
     * @param: [employeeProfile]
     * @return: boolean
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    @Transactional
    public Result updateEmployeeProfile(EmployeeProfile employeeProfile) {
        if (employeeProfile == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        if (employeeProfile.getId() == null || employeeProfile.getId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        EmployeeProfile profile = employeeProfileMapper.selectById(employeeProfile.getId());
        if (profile == null){
            return new Result(HttpStatus.BAD_REQUEST,"该员工档案不存在");
        }
        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean root = loginUser.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString());
        // 查是否有缓存
        LambdaQueryWrapper<EmployeeProfileCache> profileCacheLQW = new LambdaQueryWrapper<>();
        profileCacheLQW.eq(EmployeeProfileCache::getUserId,profile.getUserId());
        EmployeeProfileCache profileCache = profileCacheMapper.selectOne(profileCacheLQW);
        if (root){
            // 管理员，直接修改
            if (profileCache != null){
                // 有缓存,将缓存删除
                profileCacheMapper.physicsDeleteById(profileCache.getId());
            }
            BeanUtils.copyProperties(employeeProfile,profile);
            // 修改审核通过1
            profile.setEmployeeUpdateStatus(1);
            // 修改次数加1
            Integer count = profile.getEmployeeUpdateCount();
            profile.setEmployeeUpdateCount(++count);
            // 合同到期提醒，提前一个月
            // 获取一个月前的日期
            LocalDate oneMonthAgo = employeeProfile.getEmployeeContractDate().minusMonths(1);
            profile.setEmployeeContractRemindDate(oneMonthAgo);
            employeeProfileMapper.updateById(profile);
            // 创建消息通知，提醒员工档案已更新
            MessageNotification msgNotification = new MessageNotification();
            // 标题
            msgNotification.setTitle("合同已更新");
            // 内容
            msgNotification.setContent("您的合同已更新");
            // 发布人为修改人
            msgNotification.setPublisherId(loginUser.getId());
            // 接收人
            msgNotification.setReceiverId(profile.getUserId());
            // 关联id
            msgNotification.setRelevanceId(profile.getId());
            // 类型，2员工合同
            msgNotification.setMsgType(2);
            // 子菜单，档案审核
            msgNotification.setSubmenu(1);
            // 状态，待处理
            msgNotification.setStatus(0);
            msgNotificationMapper.insert(msgNotification);
            return Result.success("修改成功");
        }else {
            // 非管理员，写进缓存
            if (profileCache != null){
                // 已有缓存，更新缓存
                BeanUtils.copyProperties(employeeProfile,profileCache);
                // 缓存合同到期提醒，提前一个月
                // 获取一个月前的日期
                LocalDate oneMonthAgo = employeeProfile.getEmployeeContractDate().minusMonths(1);
                profileCache.setEmployeeContractRemindDate(oneMonthAgo);
                profileCacheMapper.updateById(profileCache);
            }else {
                // 没有缓存，创建缓存
                profileCache = new EmployeeProfileCache();
                BeanUtils.copyProperties(employeeProfile,profileCache);
                // 缓存合同到期提醒，提前一个月
                // 获取一个月前的日期
                LocalDate oneMonthAgo = employeeProfile.getEmployeeContractDate().minusMonths(1);
                profileCache.setEmployeeContractRemindDate(oneMonthAgo);
                profileCacheMapper.insert(profileCache);
            }
            // 修改状态，待审核
            profile.setEmployeeUpdateStatus(0);
            // 更新状态
            LambdaUpdateWrapper<EmployeeProfile> profileLUW = new LambdaUpdateWrapper<>();
            profileLUW.eq(EmployeeProfile::getId,profile.getId())
                    .set(EmployeeProfile::getEmployeeUpdateStatus,profile.getEmployeeUpdateStatus());
            employeeProfileMapper.update(null,profileLUW);
            // 查所有管理员
            LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
            userLQW.eq(User::getRoleId,RoleEnum.ROLE_1.getCodeToString());
            List<User> userList = userMapper.selectList(userLQW);
            if (userList.isEmpty()){
                return Result.success("申请成功");
            }
            // 查员工
            User user1 = userMapper.selectByIdWithDelete(employeeProfile.getUserId());
            // 创建消息通知，提醒所有管理员
            List<MessageNotification> msgList = new ArrayList<>();
            for (User user : userList){
                MessageNotification msg = new MessageNotification();
                msg.setId(UUID.randomUUID().toString().replaceAll("-",""));
                msg.setTitle("有新的合同修改申请待审批");
                String content = user1.getNickName()+"申请修改合同信息";
                msg.setContent(content);
                // 发布人为申请人
                msg.setPublisherId(employeeProfile.getUserId());
                // 接收人为管理员
                msg.setReceiverId(user.getId());
                // 关联id
                msg.setRelevanceId(employeeProfile.getId());
                // 类型，2员工合同
                msg.setMsgType(2);
                // 子菜单，档案审核
                msg.setSubmenu(2);
                // 状态，待处理
                msg.setStatus(0);
                // 创建时间
                msg.setCreateTime(new Date());
                msgList.add(msg);
            }
            msgNotificationMapper.insertBatch(msgList);
            return Result.success("申请成功");
        }
    }

    /**
     * @description: 管理员审核员工档案
     * @param: [state]
     * @return: boolean
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public boolean updateEmployeeProfileByAdmin(String id,boolean state) {
        //0:被替代 1:待审核 2:审核通过 3:审核失败,
        EmployeeProfile one = employeeProfileMapper.selectOne(new LambdaQueryWrapper<EmployeeProfile>()
                .eq(BaseEntity::getId, id));
        List<EmployeeProfile> profileList = employeeProfileMapper.selectList(new LambdaQueryWrapper<EmployeeProfile>()
                .eq(EmployeeProfile::getEmployeeIdcard, one.getEmployeeIdcard())
                .in(EmployeeProfile::getEmployeeUpdateStatus, 1,2));

        if (state){
            profileList.forEach(profile->{
                if (profile.getEmployeeUpdateStatus()==2){
                    profile.setEmployeeUpdateStatus(0);
                }
                if (profile.getEmployeeUpdateStatus()==1){
                    profile.setEmployeeUpdateStatus(2);
                    profile.setEmployeeUpdateCount(profile.getEmployeeUpdateCount()+1);
                }
                employeeProfileMapper.updateById(profile);
            });
            return true;
        }
        //审核失败
        profileList.forEach(profile->{
            if (profile.getEmployeeUpdateStatus()==1){
                profile.setEmployeeUpdateStatus(3);
                int i = employeeProfileMapper.updateById(profile);
            }
        });
        return true;
    }

    /**
     * @description: 管理员分页查看所有员工档案
     * @param: []
     * @return: java.util.List<aiku.numericalcontroloa.Model.AttendanceVo.EmployeeProfileVo>
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public EmployeeProfileInfoVo selectEmployeeProfileByAdmin(Page page) {
        //先查询是否有权限
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getId, userid).eq(User::getRoleId, 1);
        User one = userMapper.selectOne(wrapper);
        LambdaQueryWrapper<EmployeeProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmployeeProfile::getEmployeeUpdateStatus,1,2,3);
        queryWrapper.eq(EmployeeProfile::getDeleted,0);
        queryWrapper.orderByDesc(EmployeeProfile::getCreateTime);
        //没有超级管理员权限
        if (one==null){
            queryWrapper.eq(EmployeeProfile::getUserId,userid);
        }

        List<EmployeeProfile> selectList = employeeProfileMapper.selectPage(page, queryWrapper).getRecords();
        Long count = employeeProfileMapper.selectCount(queryWrapper);
        //临时存储map
        Map<Object, EmployeeProfile> map2 = new HashMap<>();

        selectList.forEach(emo->{
            EmployeeProfile m2 = map2.get(emo.getEmployeeIdcard());
            if(m2==null){
                map2.put(emo.getEmployeeIdcard(),emo);
            }
            if (m2!=null){
                if (m2.getEmployeeUpdateStatus()==2){
                    map2.put(emo.getEmployeeIdcard(),emo);
                }
            }
        });
        ArrayList<EmployeeProfile> arrayList = new ArrayList<>(map2.values());

        //TODO:转换为vo
        List<EmployeeProfileVo> employeeProfileVos = new ArrayList<>();
        arrayList.forEach(emplist->{
            EmployeeProfileVo profileVo = new EmployeeProfileVo();
            BeanUtils.copyProperties(emplist,profileVo);
            employeeProfileVos.add(profileVo);
        });
        EmployeeProfileInfoVo employeeProfileInfoVo = new EmployeeProfileInfoVo();
        employeeProfileInfoVo.setTotal(count);
        employeeProfileInfoVo.setEmployeeProfileVoList(employeeProfileVos);
        return employeeProfileInfoVo;
    }

    /**
     * @description: 通过id查看员工档案
     * @param: []
     * @return: java.util.List<aiku.numericalcontroloa.Model.AttendanceVo.EmployeeProfileVo>
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public EmployeeProfileVo selectEmployeeProfileById(String id) {
        EmployeeProfile employeeProfile = employeeProfileMapper.selectOne(new LambdaQueryWrapper<EmployeeProfile>()
                .eq(EmployeeProfile::getId, id)
                .eq(BaseEntity::getDeleted, 0));
        if (employeeProfile!=null){
            EmployeeProfileVo employeeProfileVo = new EmployeeProfileVo();
            BeanUtils.copyProperties(employeeProfile,employeeProfileVo);
            return employeeProfileVo;
        }
        return null;
    }


    /**
     * @description: 通过id删除员工档案
     * @param: []
     * @return: java.util.List<aiku.numericalcontroloa.Model.AttendanceVo.EmployeeProfileVo>
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public boolean deleteEmployeeProfileById(String id) {
        EmployeeProfile employeeProfile = employeeProfileMapper.selectOne(new LambdaQueryWrapper<EmployeeProfile>()
                .eq(EmployeeProfile::getId, id)
                .eq(EmployeeProfile::getDeleted, 0));
        if (employeeProfile==null){
            return false;
        }
        employeeProfile.setDeleted(1);
        System.out.println(employeeProfile.getDeleted());
        int i = employeeProfileMapper.deleteById(employeeProfile);
        return i > 0;
    }

    /**
     * @description: 查询所有未审核的员工档案
     * @param: []
     * @return:
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public EmployeeProfileInfoVo selectEmployeeProfileByState(Page pages,Integer type) {
        //先查询是否有权限
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getId, userid).eq(User::getRoleId, 1);
        User one = userMapper.selectOne(wrapper);
        LambdaQueryWrapper<EmployeeProfile> queryWrapper = new LambdaQueryWrapper<>();
        if (type!=-1){
            queryWrapper.eq(EmployeeProfile::getEmployeeUpdateStatus,type); //1为新增 2为修改 3为删除
        }
        if (type==-1){
            queryWrapper.eq(EmployeeProfile::getEmployeeUpdateStatus,1);
        }
        queryWrapper.eq(EmployeeProfile::getDeleted,0);
        queryWrapper.orderByDesc(EmployeeProfile::getCreateTime);
        //没有超级管理员权限
        if (one==null){
            queryWrapper.eq(EmployeeProfile::getUserId,userid);
        }

        List<EmployeeProfile> selectList = employeeProfileMapper.selectPage(pages, queryWrapper).getRecords();
        Long count = employeeProfileMapper.selectCount(queryWrapper);

        //TODO:转换为vo
        List<EmployeeProfileVo> employeeProfileVos = new ArrayList<>();
        selectList.forEach(emplist->{
            EmployeeProfileVo profileVo = new EmployeeProfileVo();
            BeanUtils.copyProperties(emplist,profileVo);
            employeeProfileVos.add(profileVo);
        });
        EmployeeProfileInfoVo employeeProfileInfoVo = new EmployeeProfileInfoVo();
        employeeProfileInfoVo.setEmployeeProfileVoList(employeeProfileVos);
        employeeProfileInfoVo.setTotal(count);
        return employeeProfileInfoVo;
    }

    /**
     * @description: 通过name或phone或idcard模糊查询员工档案
     * @param: []
     * @return:
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public List<EmployeeProfile> selectEmployeeProfileByNameOrPhoneOrIdCard(String name) {
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<EmployeeProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmployeeProfile::getDeleted,0); //1为新增 2为修改 3为删除
        queryWrapper.like(EmployeeProfile::getEmployeeName,name)
                .or().like(EmployeeProfile::getEmployeeEmail,name)
                .or().like(EmployeeProfile::getEmployeeIdcard,name)
                .orderByDesc(EmployeeProfile::getCreateTime);
        //先查询是否有权限
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getId, userid).eq(User::getRoleId, 1);
        User adminOne = userMapper.selectOne(wrapper);
        if (adminOne==null){
            queryWrapper.eq(EmployeeProfile::getUserId,userid);
        }
        List<EmployeeProfile> employeeProfiles = employeeProfileMapper.selectList(queryWrapper);
        //去重
        Map<Object, EmployeeProfile> map2 = new HashMap<>();
        employeeProfiles.forEach(emo->{
            EmployeeProfile m2 = map2.get(emo.getEmployeeIdcard());
            if(m2==null){
                map2.put(emo.getEmployeeIdcard(),emo);
            }
            if (m2!=null){
                if (m2.getEmployeeUpdateStatus()==2){
                    map2.put(emo.getEmployeeIdcard(),emo);
                }
            }
        });
        ArrayList<EmployeeProfile> arrayList = new ArrayList<>(map2.values());
        return arrayList;
    }

    /**
     * @description: 通过name或phone或idcard模糊查询员工档案
     * @param: []
     * @return:
     * @auther: 马
     * @date: 2024-01-16 14:25:10
     */
    @Override
    public List<EmployeeProfile> selectEmployeeProfileByStateLike(String name,Integer type) {
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<EmployeeProfile> queryWrapper = new LambdaQueryWrapper<>();
        //先查询是否有权限
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getId, userid).eq(User::getRoleId, 1);
        User adminOne = userMapper.selectOne(wrapper);
        if (adminOne==null){
            queryWrapper.eq(EmployeeProfile::getUserId,userid);
        }
        if (type!=-1){
            queryWrapper.eq(EmployeeProfile::getEmployeeUpdateStatus,type); //1为待审核 2为已通过 3为审核失败
        }
        if (type==-1){
            queryWrapper.in(EmployeeProfile::getEmployeeUpdateStatus,1,2,3); //1为待审核 2为已通过 3为审核失败
        }
        queryWrapper.eq(EmployeeProfile::getDeleted,0); //1为新增 2为修改 3为删除
        queryWrapper.like(EmployeeProfile::getEmployeeName,name)
                .or().like(EmployeeProfile::getEmployeeEmail,name)
                .or().like(EmployeeProfile::getEmployeeIdcard,name)
                .orderByDesc(EmployeeProfile::getCreateTime);
        List<EmployeeProfile> employeeProfiles = employeeProfileMapper.selectList(queryWrapper);
        //去重
        Map<Object, EmployeeProfile> map2 = new HashMap<>();
        employeeProfiles.forEach(emo->{
            EmployeeProfile m2 = map2.get(emo.getEmployeeIdcard());
            if(m2==null){
                map2.put(emo.getEmployeeIdcard(),emo);
            }
            if (m2!=null){
                if (m2.getEmployeeUpdateStatus()==2){
                    map2.put(emo.getEmployeeIdcard(),emo);
                }
            }
        });
        List<EmployeeProfile> arrayList = new ArrayList<>(map2.values());
        return arrayList;
    }

    @Override
    public Result getEmployeeProfileList(EmployeeProfileDto employeeProfileDto) {
        if (employeeProfileDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto is null)");
        }
        if (employeeProfileDto.getCurrentPage() == null || employeeProfileDto.getPageSize() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少分页参数");
        }
        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean root = loginUser.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString());
        Page<EmployeeProfile> profilePage = new Page<>(employeeProfileDto.getCurrentPage(),employeeProfileDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<EmployeeProfile> profileLQW = new LambdaQueryWrapper<>();
        profileLQW.orderByDesc(EmployeeProfile::getCreateTime);
        if (!root){
            profileLQW.eq(EmployeeProfile::getUserId,loginUser.getId());
        }
        if (employeeProfileDto.getStatus() != null) {
            profileLQW.eq(EmployeeProfile::getEmployeeStatus,employeeProfileDto.getStatus());
        }
        if (employeeProfileDto.getNickName() != null) {
            profileLQW.and(lqw ->lqw.like(EmployeeProfile::getEmployeeName,employeeProfileDto.getNickName())
                    .or().like(EmployeeProfile::getEmployeeEmail,employeeProfileDto.getNickName())
                    .or().like(EmployeeProfile::getEmployeeIdcard,employeeProfileDto.getNickName()));
        }
        List<EmployeeProfile> profileList = employeeProfileMapper.selectPage(profilePage, profileLQW).getRecords();
        List<EmployeeProfileVo> profileVoList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (profileList.isEmpty()){
            map.put("total",profilePage.getTotal());
            map.put("profileVoList",profileVoList);
            return Result.success("查询成功",map);
        }

        // 获取用户id列表
        Set<String> userIdList = profileList.stream().map(EmployeeProfile::getUserId).collect(Collectors.toSet());
        // 根据userIdList查询用户
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 根据userId获取用户对象
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

        for (EmployeeProfile profile : profileList){
            EmployeeProfileVo profileVo = new EmployeeProfileVo();
            BeanUtils.copyProperties(profile,profileVo);
            //
            User user = userMap.get(profile.getUserId());
            profileVo.setEmployeeStatus(user.getState());
            // 处理图片
            if (profile.getEmployeeContractFile() != null && !profile.getEmployeeContractFile().isEmpty()){
                profileVo.setContractUrl(profile.getEmployeeContractFile().split(";"));
            }
            if (profile.getEmployeeSecrecyFile() != null && !profile.getEmployeeSecrecyFile().isEmpty()){
                profileVo.setSecrecyUrl(profile.getEmployeeSecrecyFile().split(";"));
            }
            profileVoList.add(profileVo);
        }
        map.put("total",profilePage.getTotal());
        map.put("profileVoList",profileVoList);
        return Result.success("查询成功",map);
    }

    @Override
    public Result getEmployeeProfile(EmployeeProfileDto employeeProfileDto) {
        if (employeeProfileDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto is null)");
        }
        if (employeeProfileDto.getId() == null || employeeProfileDto.getId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[id] is null)");
        }
        EmployeeProfile employeeProfile = employeeProfileMapper.selectById(employeeProfileDto.getId());
        if (employeeProfile == null){
            return new Result(HttpStatus.BAD_REQUEST,"该员工档案不存在");
        }
        // 查员工
        User user = userMapper.selectByIdWithDelete(employeeProfile.getUserId());
        EmployeeProfileVo profileVo = new EmployeeProfileVo();
        BeanUtils.copyProperties(employeeProfile,profileVo);
        profileVo.setEmployeeStatus(user.getState());
        // 处理图片
        if (employeeProfile.getEmployeeContractFile() != null && !employeeProfile.getEmployeeContractFile().isEmpty()){
            profileVo.setContractUrl(employeeProfile.getEmployeeContractFile().split(";"));
        }
        if (employeeProfile.getEmployeeSecrecyFile() != null && !employeeProfile.getEmployeeSecrecyFile().isEmpty()){
            profileVo.setSecrecyUrl(employeeProfile.getEmployeeSecrecyFile().split(";"));
        }
        return Result.success("查询成功",profileVo);
    }

    @Override
    public Result getEmployeeProfileCache(EmployeeProfileDto employeeProfileDto) {
        if (employeeProfileDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto is nul)");
        }
        if (employeeProfileDto.getUserId() == null || employeeProfileDto.getUserId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[userId] is null)");
        }
        LambdaQueryWrapper<EmployeeProfileCache> profileCacheLQW = new LambdaQueryWrapper<>();
        profileCacheLQW.eq(EmployeeProfileCache::getUserId,employeeProfileDto.getUserId());
        EmployeeProfileCache employeeProfileCache = profileCacheMapper.selectOne(profileCacheLQW);
        if (employeeProfileCache == null){
            return new Result(HttpStatus.BAD_REQUEST,"该员工缓存档案不存在");
        }
        // 查员工
        User user = userMapper.selectByIdWithDelete(employeeProfileCache.getUserId());
        EmployeeProfileVo profileVo = new EmployeeProfileVo();
        BeanUtils.copyProperties(employeeProfileCache,profileVo);
        profileVo.setEmployeeStatus(user.getState());
        // 处理图片
        if (employeeProfileCache.getEmployeeContractFile() != null && !employeeProfileCache.getEmployeeContractFile().isEmpty()){
            profileVo.setContractUrl(employeeProfileCache.getEmployeeContractFile().split(";"));
        }
        if (employeeProfileCache.getEmployeeSecrecyFile() != null && !employeeProfileCache.getEmployeeSecrecyFile().isEmpty()){
            profileVo.setSecrecyUrl(employeeProfileCache.getEmployeeSecrecyFile().split(";"));
        }
        return Result.success("查询成功",profileVo);
    }

    @Override
    @Transactional
    public Result examineProfile(EmployeeProfileDto employeeProfileDto) {
        if (employeeProfileDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto is null)");
        }
        if (employeeProfileDto.getId() == null || employeeProfileDto.getId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[id] is null)");
        }
        if (employeeProfileDto.getCacheId() == null || employeeProfileDto.getCacheId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[cacheId] is null)");
        }
        if (employeeProfileDto.getStatus() == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[status] is null)");
        }
        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!loginUser.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())){
            return new Result(HttpStatus.FORBIDDEN,"无权访问");
        }
        // 查档案
        EmployeeProfile employeeProfile = employeeProfileMapper.selectById(employeeProfileDto.getId());
        if (employeeProfile == null){
            return new Result(HttpStatus.BAD_REQUEST,"该员工档案不存在");
        }
        // 查缓存
        EmployeeProfileCache profileCache = profileCacheMapper.selectById(employeeProfileDto.getCacheId());
        if (profileCache == null){
            return new Result(HttpStatus.BAD_REQUEST,"该员工缓存档案不存在");
        }
        // 更新状态
        employeeProfile.setEmployeeUpdateStatus(employeeProfileDto.getStatus());
        // 更新状态
        LambdaUpdateWrapper<EmployeeProfile> profileLUW = new LambdaUpdateWrapper<>();
        profileLUW.eq(EmployeeProfile::getId,employeeProfile.getId())
                .set(EmployeeProfile::getEmployeeUpdateStatus,employeeProfile.getEmployeeUpdateStatus());
        employeeProfileMapper.update(null,profileLUW);

        // 判断是否通过
        if(employeeProfile.getEmployeeUpdateStatus().equals(1)){
            // 通过
            // 将缓存覆盖到原来档案
            BeanUtils.copyProperties(profileCache,employeeProfile);
            // 修改次数加1
            Integer count = employeeProfile.getEmployeeUpdateCount();
            employeeProfile.setEmployeeUpdateCount(++count);
            // 合同到期提醒，提前一个月
            // 获取一个月前的日期
            LocalDate oneMonthAgo = employeeProfile.getEmployeeContractDate().minusMonths(1);
            employeeProfile.setEmployeeContractRemindDate(oneMonthAgo);
            // 更新
            employeeProfileMapper.updateById(employeeProfile);
            // 物理删除缓存
            profileCacheMapper.physicsDeleteById(profileCache.getId());
            // 创建消息通知，通知申请人修改通过
            MessageNotification msgNotification = new MessageNotification();
            // 标题
            msgNotification.setTitle("合同修改申请已通过");
            // 内容
            msgNotification.setContent("您的合同修改申请已通过");
            // 发布人为审核人
            msgNotification.setPublisherId(loginUser.getId());
            // 接收人
            msgNotification.setReceiverId(employeeProfile.getUserId());
            // 关联id
            msgNotification.setRelevanceId(employeeProfile.getId());
            // 类型，2员工合同
            msgNotification.setMsgType(2);
            // 子菜单，档案审核
            msgNotification.setSubmenu(2);
            // 状态，待处理
            msgNotification.setStatus(0);
            msgNotificationMapper.insert(msgNotification);
            return Result.success("修改成功");
        }else {
            // 未通过
            // 创建消息通知，通知申请人修改未通过
            MessageNotification msgNotification = new MessageNotification();
            // 标题
            msgNotification.setTitle("合同修改申请被拒绝");
            // 内容
            msgNotification.setContent("您的合同修改申请被拒绝");
            // 发布人为审核人
            msgNotification.setPublisherId(loginUser.getId());
            // 接收人
            msgNotification.setReceiverId(employeeProfile.getUserId());
            // 关联id
            msgNotification.setRelevanceId(employeeProfile.getId());
            // 类型，2员工合同
            msgNotification.setMsgType(2);
            // 子菜单，档案审核
            msgNotification.setSubmenu(2);
            // 状态，待处理
            msgNotification.setStatus(0);
            msgNotificationMapper.insert(msgNotification);
            return Result.success("修改成功");
        }
    }

    @Override
    @Transactional
    public Result deleteEmployeeProfile(EmployeeProfileDto employeeProfileDto) {
        if (employeeProfileDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto is null)");
        }
        if (employeeProfileDto.getId() == null || employeeProfileDto.getId().isEmpty()){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(employeeProfileDto[id] is null)");
        }
        EmployeeProfile employeeProfile = employeeProfileMapper.selectById(employeeProfileDto.getId());
        if (employeeProfile == null){
            return new Result(HttpStatus.BAD_REQUEST,"该档案不存在");
        }
        // 删除
        employeeProfileMapper.deleteById(employeeProfile.getId());
        // 查缓存
        LambdaQueryWrapper<EmployeeProfileCache> profileCacheLQW = new LambdaQueryWrapper<>();
        profileCacheLQW.eq(EmployeeProfileCache::getUserId,employeeProfile.getUserId());
        EmployeeProfileCache employeeProfileCache = profileCacheMapper.selectOne(profileCacheLQW);
        if (employeeProfileCache != null){
            // 删除缓存
            profileCacheMapper.physicsDeleteById(employeeProfileCache.getId());
        }
        return Result.success("删除成功");
    }

    @Override
    public Result getProfileIdList() {
        LambdaQueryWrapper<EmployeeProfile> profileLQW = new LambdaQueryWrapper<>();
        profileLQW.select(EmployeeProfile::getUserId).eq(EmployeeProfile::getDeleted,0);
        List<EmployeeProfile> employeeProfiles = employeeProfileMapper.selectList(profileLQW);
        List<String> userIdList = employeeProfiles.stream().map(EmployeeProfile::getUserId).collect(Collectors.toList());
        return Result.success("查询成功",userIdList);
    }
}




